<?php
declare(strict_types=1);

namespace App\Resource\Group\Group;


use App\Resource\Group\Members\DetailResource;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;

class Resource extends JsonResource
{
    public function toArray($request)
    {
        if(empty($this->id)){
            return [];
        }
        $bannedCountdown = 0;
        if($this->is_global_banned){
            if(!empty($this->banned_end_at)){
                $bannedCountdown = Carbon::make($this->banned_end_at)->timestamp - time();
                if($bannedCountdown <= 0){
                    $this->is_global_banned = 0;
                    $bannedCountdown = 0;
                }
            }else{
                $bannedCountdown = 0;
            }
        }

        $res = [
            "id" => $this->id,
            "city_id" => $this->city_id,
            "code" => $this->code,
            "name" =>  isset($this->member->remark) && !empty($this->member->remark) ? $this->member->remark : $this->name, // 列表显示群备注
            "real_name" => $this->name,
            "avatar" => $this->avatar,
            "cover" => $this->cover,
            "member_count" => $this->member_count,
            "allow_member_count" => $this->allow_member_count,
            "introduction" => $this->introduction,
            "user" => empty($this->user) ? null: DetailResource::make($this->user),
            "category" => \App\Resource\Group\Categoury\Resource::make($this->category),
//            "members" => \App\Resource\Group\Members\Resource::collection($this->members),
            "dynamic_images" => $this->dynamic_image ?? null,
            "bulletin" => $this->bulletin ?? null,
            "is_join" => empty($this->user) ? 0 : 1,
            "location" => $this->location,
            "is_global_banned" => $this->is_global_banned,
            "is_open_dynamic" => $this->is_open_dynamic,
            "is_open_party" => $this->is_open_party,
            "is_open_friend" => $this->is_open_friend,
            "banned_end_at" => $this->banned_end_at,
            "banned_countdown" => $bannedCountdown,
            "audit_status" => $this->audit_status ?: null,
            "created_at" => $this->created_at->toDateTimeString(),
        ];
        if (!empty($this->need_members)){
            $res['members'] = \App\Resource\Group\Members\Resource::collection($this->members);
        }
        return $res;
    }
}